package com.example.mqttledmenu;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class EditUserInfo extends AppCompatActivity {
    private static final int REQUEST_GALLERY = 100;
    private ImageView user_avatar;
    private Button upload;
    private Button submit;
    private String avatarUrl = "";

    private void initView() {
        //获取图片并展示用户当前的头像信息
        user_avatar = findViewById(R.id.user_avatar);
        upload = findViewById(R.id.upload_change);
        submit = findViewById(R.id.submit_change);
        //初始化用户头像
        Log.d("nightowl", "输出用户默认的头像：" + Config.getInstance().getAvatar());
        RequestOptions requestOptions = RequestOptions.centerCropTransform().transform(new CircleCrop());
        Glide.with(this)
                .load(Config.getInstance().getAvatar())
                .apply(requestOptions)
                .into(user_avatar);
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpenFile(v);
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发请求
                Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
                UploadService uploadService = retrofit.create(UploadService.class);
                Log.d("nightowl", "修改头像参数：" + Config.getInstance().getUserId() + "," + avatarUrl);
                Call<ResponseBody> call = uploadService.changeInfo(Config.getInstance().getUserId(), avatarUrl);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.body() != null) {
                            try {
                                String result = response.body().string();
                                JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                                if (!returnData.get("code").toString().equals("200")) {
                                    Toast.makeText(EditUserInfo.this, "服务端错误~", Toast.LENGTH_SHORT).show();
                                } else {
                                    Config.getInstance().setUserAvatar(avatarUrl);
                                    Toast.makeText(EditUserInfo.this, "头像修改成功！！", Toast.LENGTH_SHORT).show();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Log.d("nightowl", "onResponse -- > " + "返回数据为空");
                        }

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.d("nightowl", "onFailure -- > " + t.toString());
                    }
                });
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_info);
        initView();
    }

    private void saveUriToFile(Uri uri, int from) {
        Bitmap bitmap = null;
        if (uri != null) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2; // 图片宽高都为原来的二分之一，即图片为原来的四分之一
                bitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri), null, options);
                user_avatar.setImageBitmap(bitmap);
                //处理文件上传
                String filePath = FileUtils.getRealFilePath(this, uri);
                sendRequest(filePath);
            } catch (Exception e) {
                Toast.makeText(this, "上传文件失败~", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void sendRequest(String filePath) {
        File file = new File(filePath);
        String newFileName = UUID.randomUUID().toString().replace("-", "") + ".jpg";
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
        UploadService uploadService = retrofit.create(UploadService.class);
        MediaType mediaType = MediaType.parse("multipart/form-data");
        RequestBody fileBody = RequestBody.create(mediaType, file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", newFileName, fileBody);
        Call<ResponseBody> call = uploadService.upload(part);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.body() != null) {
                    try {
                        String result = response.body().string();
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        avatarUrl = returnData.get("data").toString();
                        Toast.makeText(EditUserInfo.this, "文件上传成功！", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.d("nightowl", "onResponse -- > " + "返回数据为空");
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("nightowl", "onFailure -- > " + t.toString());
            }
        });
    }

    private void OpenFile(View view) {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK); // 系统默认的图片选择程序
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, REQUEST_GALLERY);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri uri = data.getData();
        saveUriToFile(uri, REQUEST_GALLERY);
    }
}